#include <stdbool.h>
#include <stdio.h>
#include <stdint.h>
#include "menu.h"
#include "pwm/timer_pwm.h"
#include "lcd.h"
#include "key.h"
#include "i2c/mi2c.h"
#include "usart/usart.h"
#include "LDC1314/LDC1314.h"

#define RUN 20

extern void change_phrase(void);
extern void show(void);
extern void check(void);

void uartTest(void);
void pwmAdjust(void);
void timeStamp(void);
void ldc1314Test(void);
void goPath(void);
void cali(void);

Menu_t MainMenu[] =
{
	{"1.Pwm",			        M_UFunc,			pwmAdjust,				    MainMenu, NULL },
	{"2.LDC1314 test",			M_UFunc,			ldc1314Test,				MainMenu, NULL },
	{"3.I2c_test ",				M_UFunc,			i2c_test,					MainMenu, NULL },
	{"4.Uart test",				M_UFunc,			uartTest,					MainMenu, NULL },
	{"5.Time ",					M_UFunc,			timeStamp,					MainMenu, NULL },
	{"6.Go",					M_UFunc,			goPath,						MainMenu, NULL },
	{"7.cali ",					M_UFunc,			cali,						MainMenu, NULL },
	{" ",						M_Empty,			NULL,						MainMenu, NULL },
};


Menu_t *CurrentMenuPointer =  MainMenu;
void show_menu(void)
{
	uint16_t i = 0;
	TFT_Clear(BLACK);
	for(i = 0; i<MENU_NUM; i++)
	{
		TFT_String(5,i*20,WHITE,BLACK,CurrentMenuPointer[i].Name);
	}
}

void uartTest(void) {
	modUart.test();
}
void pwmAdjust(void) {
	modPwm.pwmAdjust();
}
void timeStamp(void) {
	modTimer.timeStamp();
}
void ldc1314Test(void) {
	ldc1314.test();
}
void cali(void) {
    ldc1314.cali();
}
void goPath(void) {
    uint8_t key = EMPTY_INPUT;
    uint32_t position;
    TFT_Clear(BLACK);
    char time_str[32];
    modUart.tx(RUN);
    modUart.isRunning = true;
    while(key != KEY_BACK)
    {
        key = check_key();
        TFT_String(120,5,WHITE,BLACK, (uint8_t *)"go Path.");
        sprintf(time_str, "%ld", modTimer.ui32Counter / 1000l);
        TFT_String(100, 35, WHITE, BLACK, time_str);
        TFT_String(5,65,WHITE,BLACK,modUart.memPool);
    }
}

void manage_menu(void)
{
	uint8_t key;
	if((key=check_key()) == EMPTY_INPUT)
		return;
	if(isNumber(key))
	{
		key = get_keyNum(key);
		if(key > MENU_NUM || key == 0)
			return;
		if(CurrentMenuPointer[key-1]. M_Attrib == M_SMenu)
		{
			CurrentMenuPointer = CurrentMenuPointer->next;
			show_menu();
		}
		else if(CurrentMenuPointer[key-1]. M_Attrib == M_UFunc)
		{
			CurrentMenuPointer[key-1].MenuFunc();
			show_menu();
		}
	}
	else if(key == KEY_BACK && CurrentMenuPointer->prev != NULL)
	{
		CurrentMenuPointer = CurrentMenuPointer->prev;
		show_menu();
	}
}
